// 操作共享变量会有问题的售票系统代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <pthread.h>


// 创建条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

// 创建锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int ticket = 1000;

void *route(void *arg)
{
    char *name = static_cast<char *>(arg);
    while (1)
    {
        // 加锁
        pthread_mutex_lock(&lock);

        // 等待
        pthread_cond_wait(&cond, &lock);
        if (ticket > 0) // 1. 判断
        {
            usleep(1000);                               // 模拟抢票花的时间
            printf("%s sells ticket:%d\n", name, ticket); // 2. 抢到了票
            ticket--;                                   // 3. 票数--

            // 解锁
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
        usleep(123);
    }
    return nullptr;
}

int main(void)
{
    // 创建锁
    pthread_t t1, t2, t3, t4;

    pthread_create(&t1, NULL, route, (void *)"thread 1");
    pthread_create(&t2, NULL, route, (void *)"thread 2");
    pthread_create(&t3, NULL, route, (void *)"thread 3");
    pthread_create(&t4, NULL, route, (void *)"thread 4");
    
    // 依次唤醒
    while(true)
    {
        sleep(1);
        pthread_cond_signal(&cond);
    }

    // 集体唤醒
    //while(true)
    //{
    //    sleep(1);
    //    pthread_cond_broadcast(&cond); 
    //}


    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}